//
//  ConnectWifiViewController.m
//  
//
//  Created by apple  on 17/7/17.
//  Copyright © 2017年 JMZ. All rights reserved.
//

#import "ConnectWifiViewController.h"
#import "BottomSheetView.h"
#import "GuidConnectViewController.h"
#import "LoginAuthViewController.h"
#import "HelpWebViewController.h"
#import "ShareWiFiView.h"
#import "animationView.h"
#import "TQLocationConverter.h"

typedef enum {
    TreeBearAP = 0,
    OtherAP
}APType;

static NSString *CellID = @"CellID";

@interface ConnectWifiViewController ()<UIWebViewDelegate,UITableViewDelegate,UITableViewDataSource,CLLocationManagerDelegate,BottomSheetViewDelegate>

@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) UILabel *ssidLabel;
@property (nonatomic, strong) UILabel *wifistatusLabel;
@property (nonatomic, strong) UIButton *authButton;
@property (nonatomic, strong) UITableView *wifiTableView;
@property (nonatomic, strong) BottomSheetView *bottomSheetView;
//关闭按钮
@property (nonatomic, strong) UIBarButtonItem *closeItem;
@property (nonatomic, strong) UIWebView *webView;

@property (nonatomic, strong) ShareWiFiView *shareWiFiView;

//定位管理器
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) NSMutableArray *wifiListArray;
@property (nonatomic, strong) NSDictionary *wifiDict;

@property (nonatomic, strong) NSIndexPath *selectIndex;

@property (nonatomic, assign) BOOL netWorkOK;
@property (nonatomic, assign) BOOL hadLoaction;//用来判断是否已经获取过一次列表信息了

@property (nonatomic, assign) APType apType;

@end

@implementation ConnectWifiViewController

- (UIWebView *)webView
{
    if (!_webView) {
        _webView = [[UIWebView alloc] init];
    }
    
    return _webView;
}

- (BottomSheetView *)bottomSheetView
{
    if (!_bottomSheetView) {
        _bottomSheetView = [[BottomSheetView alloc] init];
        
    }
    
    return _bottomSheetView;
}

- (CLLocationManager *)locationManager
{
    if (!_locationManager) {

        //定位功能
        if([CLLocationManager locationServicesEnabled])
        {
            if (_locationManager == nil) {
                _locationManager = [[CLLocationManager alloc] init];
                _locationManager.delegate = self;
                _locationManager.distanceFilter = 1.0;
                if (IOS8) {
                    [_locationManager requestWhenInUseAuthorization];
                }
                
                //选择定位的方式为最优的状态，他又四种方式在文档中能查到
                _locationManager.desiredAccuracy=kCLLocationAccuracyBest;
            }
    
        }


    }
    
    return _locationManager;
    
}

- (UIBarButtonItem *)closeItem
{
    if (!_closeItem) {
        _closeItem = [[UIBarButtonItem alloc] initWithTitle:@"< 返回 " style:UIBarButtonItemStylePlain target:self action:@selector(closeNative)];
        _closeItem.tintColor = [UIColor whiteColor];
    }
    return _closeItem;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UINavigationBar *bar = [UINavigationBar appearance];
    //设置显示的颜色
    bar.barTintColor = [UIColor hexColor:@"63B8FF"];
    //设置字体颜色
    bar.tintColor = [UIColor whiteColor];
    [bar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
    
//    self.navigationController.navigationBarHidden = NO;
//    self.navigationController.navigationBar.barStyle = UIBarStyleBlackTranslucent;
   
    [self addLeftButton];
    
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc]init]];
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_right_share"] style:UIBarButtonItemStylePlain target:self action:@selector(shareWiFi:)];
    
    self.navigationItem.rightBarButtonItem = rightItem;

//    self.apType = TreeBearAP;
    
    NSURL *url = [NSURL URLWithString:@"http://weibo.com"];//http://weibo.com
    [self.webView loadRequest:[NSURLRequest requestWithURL:url]];
    self.webView.delegate = self;
    
    // Do any additional setup after loading the view.
    [self initMainView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(AppDidBecomeActive)
                                                 name:UIApplicationDidBecomeActiveNotification object:nil];

    [self.locationManager startUpdatingLocation];
    
    _shareWiFiView = [[ShareWiFiView alloc] init];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self loadInitMainData];
    
    //去除导航栏下方的横线
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc]init]
                                                  forBarMetrics:UIBarMetricsDefault];
    
}

- (void)ConWiFiViewRefre:(id)notification
{
    NSLog(@"切换到WiFi列表页的时候刷新");
    [self loadInitMainData];
}

- (void)AppDidBecomeActive
{
    [self loadInitMainData];
}

- (void)loadInitMainData
{
    [self.locationManager startUpdatingLocation];
    
    NSURL *url = [NSURL URLWithString:@"http://weibo.com"];
    [self.webView loadRequest:[NSURLRequest requestWithURL:url]];
    
    _wifiDict = [NSDictionary dictionaryWithDictionary:[NetWordUtil fetchSSIDInfo]];
    _hadLoaction = NO;
    [self getLocationWiFiList];
    //判断当前的网络类型
    [NetWordUtil currentNetWordStatus:^(NSInteger status){
        if (status == 1) {//移动网络2G、3G、4G
            NSLog(@"当前使用的是流量数据，扫描周边的WiFi匹配后台密码");
            _authButton.hidden = YES;
            _ssidLabel.text = @"当前使用的是数据流量";
            _wifistatusLabel.text =@"";
            
        }else if(status == 2) {//WiFi
            NSLog(@"当前使用的是WiFi");
            //http://connect.rom.miui.com/generate_204
            //http://g.cn/generate_204
            [HttpClient requestJson:@"http://connect.rom.miui.com/generate_204" params:nil success:^(NSDictionary *data){
                NSLog(@"可以直接访问网页");
                _authButton.hidden = YES;
                _wifistatusLabel.text =@"连接成功";
                _ssidLabel.text = [NetWordUtil getWiFiSSID];
                _netWorkOK = YES;
                
            } failure:^(NSError *error){
                if (error.code != 204) {//如果返回码为204，就证明手机当前连接的wifi，是不需要进行portal验证的
                    NSLog(@"当前的WiFi无法连接网络");
                    _authButton.hidden = NO;
                    _ssidLabel.text = @"当前WiFi签到认证后才可上网";
                    _wifistatusLabel.text = [NetWordUtil getWiFiSSID];
                    
//                    if ([StoreUtil getUserPhoneNumber].length == 0 && ![[NetWordUtil getWiFiSSID] isEqual:@"0"]) {
//                        LoginAuthViewController *loginAuthView = [[LoginAuthViewController alloc] init];
//
//                        if([Treebear isEqual:[StoreUtil getApType]]) {
//                            loginAuthView.authType = Treebear;
//
//                        }else {
//                            loginAuthView.authType = SundRay;
//                        }
//
//                        [self.navigationController pushViewController:loginAuthView animated:YES];
//                    }
                    
                }
            }];
            
        }else {
            NSLog(@"没有网络，请检查是否已经打开网络");
            _ssidLabel.text = @"没有网络，请检查是否已经连接网络";
        }
    }];
}

#pragma mark - 进行上网认证
- (void)gotoAuthView
{
    if ([StoreUtil getUserPhoneNumber].length == 0) {
        LoginAuthViewController *loginAuthView = [[LoginAuthViewController alloc] init];
        
        if([Treebear isEqual:[StoreUtil getApType]]) {
            loginAuthView.authType = Treebear;
            
        }else {
            loginAuthView.authType = SundRay;
        }
        
        [self.navigationController pushViewController:loginAuthView animated:YES];
    }else {
        [self startLoadAnimation];
        if([Treebear isEqual:[StoreUtil getApType]]) {
            [self submitWiFiAllow];
            
        }else {
            [self submitSunRayAuth];
        }
    }

}

- (void)shareWiFi:(id)sender
{
    [self shareWiFiAction:[NetWordUtil getWiFiSSID]];
}

- (void)shareWiFiAction:(NSString *)ssid
{
//    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"分享：%@ ",ssid] message:nil preferredStyle:UIAlertControllerStyleAlert];
//    
//    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
//    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"分享" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
//        UITextField *textField = alertController.textFields[0];
//        if (textField.text.length != 0) {
//            NSDictionary *location = [StoreUtil getUserLocation];
//            NSString *point = [NSString stringWithFormat:@"%@,%@",location[param_lng],location[param_lat]];
//            NSString *BSSID = @"";
//            if ([ssid isEqual:[NetWordUtil getWiFiSSID]]) {
//                BSSID = [NetWordUtil getWiFiMac];
//            }
//            [self showLoadingView];
//            NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:ssid,param_ssid,textField.text,param_pwd,@"WAP/WAP2",param_security,point,param_strPoiont,BSSID,param_bssid, nil];
//            [HttpClient requestPost:kUrlAddUpdate params:params success:^(NSInteger result){
//                NSLog(@"--->分享WiFi密码成功：%ld",result);
//                [self toast:@"分享热点密码成功"];
//                [self getLocationWiFiList];
//                [self hideLoadingView];
//            } failure:^(NSError *error){
//                NSLog(@"分享WiFi密码失败：%@",[Utile transErrorInfo:error]);
//                [self hideLoadingView];
//            }];
//        }
//    }];
//    
//    [alertController addAction:cancelAction];
//    [alertController addAction:okAction];
//    [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField){
//        textField.placeholder = @"输入热点密码";
//    }];
//    
//    
//    [self presentViewController:alertController animated:YES completion:nil];
    
    __weak __typeof__(self)weakSelf = self;
    [_shareWiFiView showInView:self.view withSSID:ssid];
    _shareWiFiView.shareWiFiViewClick = ^(NSInteger tag, NSString *password){
        if (tag == 1002) {
            if (password.length == 0) {
                [Utile showToast:weakSelf.view withText:@"请输入热点密码"];
            
                return ;
            }
            NSDictionary *location = [StoreUtil getUserLocation];
            NSString *point = [NSString stringWithFormat:@"%@,%@",location[param_lng],location[param_lat]];
            NSString *BSSID = @"";
            if ([ssid isEqual:[NetWordUtil getWiFiSSID]]) {
                BSSID = [NetWordUtil getWiFiMac];
            }
            
            NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:ssid,param_ssid,password,param_pwd,@"WAP/WAP2",param_security,point,param_strPoiont,BSSID,param_bssid, nil];
            [HttpClient requestPost:kUrlAddUpdate params:params success:^(NSInteger result){
                NSLog(@"--->分享WiFi密码成功：%ld",result);
           
                [Utile showToast:weakSelf.view withText:@"分享热点密码成功"];
                [weakSelf getLocationWiFiList];
                
            } failure:^(NSError *error){
                NSLog(@"分享WiFi密码失败：%@",[Utile transErrorInfo:error]);
               
            }];
        }else if (tag == 1003) {
            NSLog(@"点击了分享计划了");
            [weakSelf.navigationController pushViewController:[[HelpWebViewController alloc] init] animated:YES];
        }
    };

}

- (void)initMainView
{
//    _wifiListArray = [NSArray arrayWithObjects:@"FJMZ",@"FJMZ_5G",@"Jmz1",@"Jmz2",@"JMZGO",@"Test",@"JMZGO", nil];
    
    _topView = [[UIView alloc] init];
    _topView.backgroundColor = [UIColor hexColor:@"63B8FF"];
    [self.view addSubview:_topView];
    CGFloat navigationHeight = self.navigationController.navigationBar.frame.size.height;
    
    _wifistatusLabel = [UILabel new];
    _wifistatusLabel.textColor = [UIColor hexColor:@"4682B4"];
    _wifistatusLabel.font = [UIFont systemFontOfSize:16];
//    _wifistatusLabel.text = @"连接成功";
    [_topView addSubview:_wifistatusLabel];
    [_wifistatusLabel mas_makeConstraints:^(MASConstraintMaker *make){
        make.centerY.equalTo(_topView.mas_centerY);
        make.centerX.equalTo(_topView.mas_centerX);
        make.height.offset(22);
    }];
    
    _ssidLabel = [UILabel new];
    _ssidLabel.textColor = [UIColor whiteColor];
    _ssidLabel.font = [UIFont systemFontOfSize:20];
    //    _ssidLabel.text = _wifiDict[@"SSID"];
    [_topView addSubview:_ssidLabel];
    [_ssidLabel mas_makeConstraints:^(MASConstraintMaker *make){
        make.centerX.equalTo(_topView.mas_centerX);
        make.bottom.equalTo(_wifistatusLabel.mas_top).offset(-7);
        
    }];
    
    _authButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _authButton.backgroundColor = [UIColor whiteColor];
    [_authButton setTitle:@"去签到上网" forState:UIControlStateNormal];
    [_authButton setTitleColor:[UIColor hexColor:@"63B8FF"] forState:UIControlStateNormal];
    _authButton.layer.cornerRadius = 20;
    _authButton.hidden = YES;
    [_authButton addTarget:self action:@selector(gotoAuthView) forControlEvents:UIControlEventTouchUpInside];
    [_topView addSubview:_authButton];
    [_authButton mas_makeConstraints:^(MASConstraintMaker *make){
        make.centerX.equalTo(_topView.mas_centerX);
        make.top.equalTo(_wifistatusLabel.mas_bottom).offset(5);
        make.width.offset(ScreenW/2);
        make.height.offset(35);
    }];
    
//    UIButton *shareWiFi = [UIButton buttonWithType:UIButtonTypeCustom];
//    shareWiFi.backgroundColor = [UIColor clearColor];
//    [shareWiFi setTitle:@"共享WiFi" forState:UIControlStateNormal];
//    [shareWiFi setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
////    shareWiFi.layer.cornerRadius = 20;
//    [shareWiFi addTarget:self action:@selector(shareWiFi:) forControlEvents:UIControlEventTouchUpInside];
//    [_topView addSubview:shareWiFi];
//    [shareWiFi mas_makeConstraints:^(MASConstraintMaker *make){
//        make.centerY.equalTo(_authButton.mas_centerY);
//        make.bottom.equalTo(_topView.mas_bottom).offset(-10);
//        make.right.equalTo(_topView.mas_right).offset(-10);
//        make.height.offset(40);
//    }];
    
    [_topView mas_makeConstraints:^(MASConstraintMaker *make){
//        make.top.equalTo(self.view);
        make.topMargin.offset(10);
        make.bottom.equalTo(_authButton.mas_bottom).offset(7);
        make.width.equalTo(self.view);
    }];


    _wifiTableView = [UITableView new];
    _wifiTableView.delegate = self;
    _wifiTableView.dataSource = self;
//    [_wifiTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:CellID];
    [self.view addSubview:_wifiTableView];
    [_wifiTableView mas_makeConstraints:^(MASConstraintMaker *make){
        make.top.equalTo(_topView.mas_bottom);
        make.bottom.equalTo(self.view.mas_bottom).offset(-7);
        make.width.offset(ScreenW);
        
    }];
    
    self.wifiTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        //Call this Block When enter the refresh status automatically
        [self getLocationWiFiList];
    }];
    
    self.wifiTableView.tableFooterView = [[UIView alloc] init];

}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear: animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"AVSystemController_SystemVolumeDidChangeNotification" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
    
}

- (void)startLoadAnimation
{
    [animationView showInView:self.view];
}

- (void)stopLoadAnimation
{
    [animationView dismiss];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    [webView stringByEvaluatingJavaScriptFromString:@"checkAppLoad();"];
    NSString *url = request.URL.absoluteString;
    NSLog(@"--->shouldLoadURL:%@",url);
    if ([url rangeOfString:@"wifi.jmzgo.com"].location != NSNotFound) {
        NSString *token = [Utile getParamFromURL:Vtoken webaddress:url];
        NSString *guid = [Utile getParamFromURL:Guid webaddress:url];
        
        NSString *aptype = @"";
        if([url rangeOfString:@"/Treebear/"].location != NSNotFound)
        {
            aptype = Treebear;
        }else {
            aptype = SundRay;
        }
        
        //if([url rangeOfString:@"/SundRay/"].location != NSNotFound)
//        NSString *aptype = [Utile getParamFromURL:ApType webaddress:url];

        NSLog(@"--->获取到的参数：token:%@  \nguid:%@  \naptyoe:%@",token,guid,aptype);

        [StoreUtil saveVtoken:token withGuid:guid withApType:aptype];
        
        return NO;
        
    }else if([url rangeOfString:@"portal.witown.com"].location != NSNotFound) {
        NSString *token = [Utile getParamFromURL:Vtoken webaddress:url];
        NSString *guid = [Utile getParamFromURL:Guid webaddress:url];
        NSString *aptype = Treebear;
        
        [StoreUtil saveVtoken:token withGuid:guid withApType:aptype];
    }else if([url rangeOfString:@".wifi.com"].location != NSNotFound) {
        NSString *token = [Utile getParamFromURL:Vtoken webaddress:url];
        NSString *guid = [Utile getParamFromURL:Guid webaddress:url];
        NSString *aptype = SundRay;
        
        [StoreUtil saveVtoken:token withGuid:guid withApType:aptype];
    }
    
    return YES;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [webView stringByEvaluatingJavaScriptFromString:@"checkAppLoad();"];
}

#pragma mark - 添加关闭按钮
- (void)addLeftButton
{
    self.navigationItem.leftBarButtonItem = self.closeItem;
}

- (void)closeNative
{
//    UITabBarController *tab2= self.tabBarController;
//    
//    self.hidesBottomBarWhenPushed = NO;
//    self.navigationController.navigationBarHidden = YES;
//    [self.navigationController popToRootViewControllerAnimated:NO];
//    [tab2 setSelectedIndex:0];
    
//    self.navigationController.navigationBarHidden = YES;
    [self.navigationController popViewControllerAnimated:YES];
    
}

#pragma mark -监听系统的音量调节
- (void)volumeChanged:(NSNotification *)notification
{
    // service logic here.
    NSLog(@"监听的音量：%@",notification);
}

#pragma mark- 连接上WiFi后，将SSID和路由器的Mac传给服务器，更新热点坐标
- (void)submitSSIDMacToServer
{
    NSDictionary *location = [StoreUtil getUserLocation];
    NSString *point = [NSString stringWithFormat:@"%@,%@",location[param_lng],location[param_lat]];
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NetWordUtil fetchWiFiName],param_ssid,point,param_point,[NetWordUtil getWiFiMac],param_bssid, nil];
    [HttpClient requestPost:kUrlUpdateWifiLocationUrl params:params success:^(NSInteger result){
        NSLog(@"----》更新SSID坐标地址成功：%ld",result);
        
//        self.hidesBottomBarWhenPushed = NO;
//        self.navigationController.navigationBarHidden = YES;
//        [self.navigationController popToRootViewControllerAnimated:NO];
        
//        if(_netWorkOK && _wifiListArray.count > 0)
        
        
//            [self.tabBarController setSelectedIndex:1];
        
        
    } failure:^(NSError *error){
        NSLog(@"更新SSID坐标和Mac失败：%@",error);
        
        NSLog(@"更新SSID坐标和Mac失败11111:%@",[Utile transErrorInfo:error]);
    }];
}

#pragma mark - 获取当前位置周边的WiFi
- (void)getLocationWiFiList
{
    NSDictionary *location = [StoreUtil getUserLocation];
    if (location.count != 0) {
        _hadLoaction = YES;
        NSString *point = [NSString stringWithFormat:@"%@,%@",location[param_lng],location[param_lat]];
        NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:point,param_point, nil];
        [HttpClient postWithURL:kUrlGetWiFiForLocal params:params success:^(id data){
            NSLog(@"获取WIFi密码返回的原始信息：%@",data);
            if ([data isKindOfClass:[NSData class]]) {
                data = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
                NSLog(@"获取WIFi密码返回的重新解析后的信息：%@",data);
                
            }
            
            NSArray *wifiarray = data[@"wifilist"];
            _wifiListArray = [NSMutableArray array];
            for (NSDictionary *dict in wifiarray) {
                NSString *pas = dict[@"wifipas"];
                if (![pas isKindOfClass:[NSNull class]] && pas.length !=  0) {
                    [_wifiListArray addObject:dict];
                }
            }
            
            if (_wifiListArray.count > 0) {
                [NetWordUtil scanWifiInfos:_wifiListArray];
            }
            
            [self.wifiTableView.mj_header endRefreshing];
            [self.wifiTableView reloadData];
            
        } failure:^(NSError *error){
            [self.wifiTableView.mj_header endRefreshing];
        }];
        
    }
}

#pragma mark - 获取选择的WiFi的密码
- (void)getWiFiPassword:(NSString *)ssid
{
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:ssid,param_par, nil];
    [HttpClient requestJson:kUrlGetWiFiListUrl params:params success:^(NSDictionary *data){
        NSLog(@"获取WIFi密码返回的原始信息：%@",data);
        if ([data isKindOfClass:[NSData class]]) {
            NSString *receiveStr = [[NSString alloc]initWithData:(NSData *)data encoding:NSUTF8StringEncoding];
            NSData *data1 = [receiveStr dataUsingEncoding:NSUTF8StringEncoding];
            data = [NSJSONSerialization JSONObjectWithData:data1 options:NSJSONReadingMutableLeaves error:nil];
            NSLog(@"获取WIFi密码返回的重新解析后的信息：%@",data);

        }

        NSArray *wifiList = data[@"wifilist"];
        
        if (wifiList.count == 0) {
            [Utile showToast:self.view withText:@"当前WIFi没有信息记录"];
            return ;
        }
        
        if (wifiList.count ==1) {
            NSDictionary *dict = wifiList[0];
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"WiFi信息" message:[NSString stringWithFormat:@"%@ 密码为：%@",dict[@"wifisid"],dict[@"wifipas"]] preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"去粘贴" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
                NSString * urlString = @"App-Prefs:root=WIFI";
                
                if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:urlString]]) {
                    
                    if ([[UIDevice currentDevice].systemVersion doubleValue] >= 10.0) {
                        
                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString] options:@{} completionHandler:nil];
                        
                    } else {
                        
                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
                        
                    }
                    
                }
            }];
            
            [alertController addAction:cancelAction];
            [alertController addAction:okAction];
            
            [self presentViewController:alertController animated:YES completion:nil];

        }else{
            
        }

    } failure:^(NSError *error){
        NSLog(@"获取WIFi密码返回的错误：%@",[Utile transErrorInfo:error]);
    }];
}

/**
 * 提交周边的WiFi信息到服务器
 */
- (void)submitWiFiListInfo:(NSString *)ssid
{
//    NSString *url = @"http://open.witown.com/router?method=treebear.merchant.portal.auth.url.get&merchantid=8aafb0565d3487e9015d39df6e510037";
    
    /*NSString *url = kUrlGetWiFiListUrl;
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:ssid,param_par, nil];
    
    [HttpClient requestJson:url params:params success:^(NSDictionary *data){
        NSLog(@"success:%@",data);
        
    } failure:^(NSError *error){
        NSLog(@"error11111:%@",error.description);
        NSData * data = error.userInfo[@"com.alamofire.serialization.response.error.data"];
        NSString * str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"服务器的错误原因11111:%@",str);
    }];*/
    
}

#pragma mark -判断tableView中的ssid是否是当前连接的WIFi
- (BOOL)isConnectWiFi:(NSString *)ssid
{
    if ([ssid isEqual:[NetWordUtil getWiFiSSID]]) {
        return YES;
    }
    return NO;
}

#pragma mark -UITableView回调
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _wifiListArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30.f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *header = [UIView new];
    header.backgroundColor = [UIColor whiteColor];
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.frame = CGRectMake(15, 0, 200, 30);
    titleLabel.font = [UIFont systemFontOfSize:14];
    titleLabel.textColor = [UIColor hexColor:@"CCCCCC"];
    titleLabel.text = @"附近可能存在的商家WiFi";
    [header addSubview:titleLabel];
    return header;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    // Configure the cell...
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle: UITableViewCellStyleValue1
                                      reuseIdentifier:CellID];
    }
    
    NSDictionary *dict = _wifiListArray[indexPath.row];
    cell.textLabel.text = dict[@"wifisid"];
    //左边按钮
//    cell.imageView.image = [UIImage imageNamed:@"icon_tabbar_marketpage_selected"];
    
    //修改右边图片
//    UIImageView *rightImg = [[UIImageView alloc] init];
    if ([self isConnectWiFi:dict[@"wifisid"]]) {
//        rightImg.image = [UIImage imageNamed:@"icon_connect"];
        cell.detailTextLabel.text = @"已连接";
    }else {
//        rightImg.image = [UIImage imageNamed:@"icon_key"];
        cell.detailTextLabel.text = @"可连接";
    }
//    rightImg.frame = CGRectMake(0, 0, 25, 25);
//    cell.accessoryView = rightImg;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    _selectIndex = indexPath;
    self.bottomSheetView.delegate = self;
    
    [self.bottomSheetView showInView:self.view withSSID:_wifiListArray[indexPath.row][@"wifisid"]];
    
//    [self getWiFiPassword:_wifiListArray[indexPath.row]];
    

}

#pragma mark - 请求树熊WiFi网络上网
- (void)submitWiFiAllow
{
    if ([StoreUtil getVtoken] == nil) {
        [Utile showToast:self.view withText:@"Token为nil"];
        return;
    }
    
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:[StoreUtil getVtoken],param_token,[StoreUtil getGuid],param_strguid, nil];
    
    [HttpClient requestJson:kUrlGetWiFiAllow params:params success:^(NSDictionary *data){
        NSLog(@"--->请求上网的返回：%@",data);
        NSInteger msg = [data[@"code"] integerValue];
        if (msg == 1) {
            [self submitSaveUserLocation];
        }else if (msg == 0) {
            [Utile showToast:self.view withText:data[@"msg"]];
        }
        [self stopLoadAnimation];
    } failure:^(NSError *error){
        NSLog(@"请求上网出错了:%@",error);
        [self stopLoadAnimation];
        [Utile showToast:self.view withText:[NSString stringWithFormat:@"请求放行出错：%@",error.description]];
    }];
}

#pragma mark - 提交认证到信锐接口
- (void)submitSunRayAuth
{
    NSString *macAddress = [NetWordUtil getWiFiMac];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd-HH:mm:ss"];
    NSDate *datenow = [NSDate date];
    NSString *time = [formatter stringFromDate:datenow];
    NSString *str = [NSString stringWithFormat:@"n=%@&u=%@&t=%@",macAddress,macAddress,time];
    NSString *encryptStr = [NSString stringWithFormat:@"%@&l=%ld",str,str.length];
    NSString *encrypt = [FormUtil convertStringToHexStr:encryptStr];
    NSLog(@"请求的参数:%@  \n加密后的16进制：%@",encryptStr,encrypt);
    // 请求地址
    NSString* url = [NSString stringWithFormat:@"%@?href=%@&id=%@", kUrlSundRayAuthUrl,encrypt,SundRayID];
    NSLog(@"开始请求");
    [HttpClient requestGet:url params:nil success:^(NSObject *response){
        NSLog(@"success:%@",response);
        
        [self submitSaveUserLocation];
        
        [self stopLoadAnimation];
    } failure:^(NSError *error){
        [self stopLoadAnimation];
        if (error.code == -1001) {
            NSLog(@"请求超时");
            [Utile showToast:self.view withText:@"认证超时"];
        }
    }];
    
}


- (void)submitSaveUserLocation
{
    NSDictionary *locationDic = [StoreUtil getUserLocation];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NetWordUtil fetchWiFiName],param_ssid,locationDic[param_lng],param_lng,locationDic[param_lat],param_lat,[StoreUtil getGuid],param_strGuid, nil];
    [HttpClient requestJson:kUrlSaveUserLocation params:params success:^(NSDictionary *data){
        
        if ([data isKindOfClass:[NSData class]]) {
            
            data = [NSJSONSerialization JSONObjectWithData:(NSData*)data options:NSJSONReadingMutableLeaves error:nil];
            
        }
        NSInteger msg = [data[@"msg"] integerValue];
        if (msg == 1) {
            NSLog(@"保存用户SSID成功");
            _authButton.hidden = YES;
            _ssidLabel.text = _wifiDict[@"SSID"];
            _wifistatusLabel.text =@"连接成功";
            [Utile showToast:self.view withText:@"签到认证成功，可以上网了"];
            
            [self submitSSIDMacToServer];
        }
        
    } failure:^(NSError *error){
        [Utile showToast:self.view withText:error.description];
    }];
}

#pragma mark - 点击广告的回调
- (void)clickAdAction:(NSInteger)index
{
    NSLog(@"用户点击了第%ld个广告了",index+1);
}

#pragma mark -广告播放完了
- (void)adScrollerEnd
{
    self.tabBarController.tabBar.hidden = NO;
//    [self playSoundEffect:@"radio.mp3"];
    if (_netWorkOK) {
        [self submitSSIDMacToServer];
    }
//    [_player play];
}

#pragma mark-实现定位代理更新位置成功回调
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    CLLocationCoordinate2D coordinate = newLocation.coordinate;
    
    //判断是否在中国
    if (![TQLocationConverter isLocationOutOfChina:coordinate])
    {
        //将WGS-84转为GCJ-02(火星坐标)
        coordinate = [TQLocationConverter transformFromWGSToGCJ:coordinate];
        
        //将GCJ-02(火星坐标)转为百度坐标
        coordinate = [TQLocationConverter transformFromGCJToBaidu:coordinate];
        
        //将百度坐标转为GCJ-02(火星坐标)
        //    coordinate = [TQLocationConverter transformFromBaiduToGCJ:coordinate];
        
        //将GCJ-02(火星坐标)转为WGS-84
        //    coordinate = [TQLocationConverter transformFromGCJToWGS:coordinate];
        
        NSDictionary *locationDic = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%f",coordinate.longitude],param_lng,[NSString stringWithFormat:@"%f",coordinate.latitude],param_lat, nil];
        [StoreUtil saveUserLocation:locationDic];
        
        NSLog(@"转换后经度：%f", coordinate.longitude);
        NSLog(@"转换后纬度：%f", coordinate.latitude);
        
        if(!_hadLoaction)
            [self getLocationWiFiList];
    }
    
//    NSLog(@"经度：%f", newLocation.coordinate.longitude);
//    NSLog(@"纬度：%f", newLocation.coordinate.latitude);

    CLGeocoder * geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        
        NSDictionary *locationInfo = [[NSDictionary alloc] init];
        for (CLPlacemark * placemark in placemarks) {
            locationInfo = [placemark addressDictionary];
        }
//        NSLog(@"当前定位：%@",locationInfo);
        
        
    }];
    
    [self.locationManager stopUpdatingLocation];
}

#pragma mark -定位代理失败回调
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"定位失败：%@", error);
}

/**
 * 播放完成回调函数 *
 * @param soundID 系统声 ID
 * @param clientData 回调时传递的数据
 
 */

/**
 * 播放音效文件
 *
 * @param name 音频文件名称 */
-(void)playSoundEffect:(NSString *)name
{
    NSString *audioFile=[[NSBundle mainBundle] pathForResource:name ofType:nil];
    NSURL *fileUrl=[NSURL fileURLWithPath:audioFile];
    //1.获得系统声音ID
    SystemSoundID soundID = 0;
    /**
     * inFileUrl: 音频文件url
     * outSystemSoundID:声 id(此函数会将音效文件加入到系统音频服务中并返回一个长整形ID) 
     */
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)(fileUrl), &soundID);
    //如果需要在播放完之后执行某些操作,可以调用如下方法注册一个播放完成回调函数
//    AudioServicesAddSystemSoundCompletion(soundID, NULL, NULL, soundCompleteCallback, NULL);
    //2.播放音频
//    AudioServicesPlaySystemSound(soundID);//播放音效
    // AudioServicesPlayAlertSound(soundID);//播放音效并震动
    
    
}

#pragma mark - BottomSheetView回调
- (void)bottomSheetAction:(int)tag
{
    [self.bottomSheetView disMissView];
    NSDictionary *dict = _wifiListArray[_selectIndex.row];
    if (tag == 1) {//直接连接
        
//        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
//        NSString *pasw = dict[@"wifipas"];
//        if (![pasw isKindOfClass:[NSNull class]]) {
//            pasteboard.string = pasw;
//        }else {
//            [self toast:@"选择的SSID密码为nil"];
//        }
//        
//        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"WiFi信息" message:[NSString stringWithFormat:@"%@ 密码已经自动复制",dict[@"wifisid"]] preferredStyle:UIAlertControllerStyleAlert];
//        //,dict[@"wifipas"]
//        
//        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
//        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"去粘贴" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
//            NSString *urlString = @"App-Prefs:root=WIFI";
//            
//            if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:urlString]]) {
//                
//                if ([[UIDevice currentDevice].systemVersion doubleValue] >= 10.0) {
//                    
//                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString] options:@{} completionHandler:nil];
//                    
//                } else {
//                    
//                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
//                    
//                }
//                
//            }
//        }];
//        
//        [alertController addAction:cancelAction];
//        [alertController addAction:okAction];
//        
//        [self presentViewController:alertController animated:YES completion:nil];
        
        GuidConnectViewController *guidView = [[GuidConnectViewController alloc] init];
        [self.navigationController pushViewController:guidView animated:YES];
        
    }else {//分享
        [self shareWiFiAction:dict[@"wifisid"]];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
